package com.zhiyun.hxzy.controller.user;

import com.zhiyun.hxzy.domain.*;
import com.zhiyun.hxzy.domain.queryvo.EditorWangResult;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.service.HomeWorkService;
import com.zhiyun.hxzy.service.SchoolService;
import com.zhiyun.hxzy.service.StudentService;
import com.zhiyun.hxzy.service.TeacherService;
import com.zhiyun.hxzy.util.Base64ToMultipartUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user/homework")
public class UserHomeWorkController {
    @Autowired
    private HomeWorkService homeWorkService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private TeacherService teacherService;

    //上传封面
    @RequestMapping("/upload")
    public @ResponseBody
    Result uploadUimg(String file) throws Exception {
        try {
            MultipartFile multipartFile = Base64ToMultipartUtil.base64ToMultipart(file);
            long size = multipartFile.getSize();
            if (size <= 1024 * 1024) {
                return homeWorkService.uploadUimg(multipartFile);
            }
            return new Result("数据超过1M，请重新上传!", false);
        } catch (Exception e) {
            return new Result("数据超过1M，请重新上传!", false);
        }

    }

    //上传图片
    @RequestMapping("/upload2")
    public @ResponseBody
    EditorWangResult uploadUimg(HttpServletRequest request, MultipartFile file) throws Exception {
        Result result = homeWorkService.uploadUimg(file);
        String[] str = {result.getMessage().toString()};
        EditorWangResult editorWangResult = new EditorWangResult(str);
        return editorWangResult;
    }

    //找到老师要点评的作业
    @RequestMapping("/findById")
    public ModelAndView findById(HttpServletRequest request, Long homeworkId) {
        ModelAndView modelAndView = new ModelAndView();
        Homework homework = homeWorkService.findById(homeworkId);
        modelAndView.getModelMap().addAttribute("homework", homework);//查询到的类型放到session中
        modelAndView.getModelMap().addAttribute("teacher", (Teacher) request.getSession().getAttribute("teacher"));
        List<Dictionary> assess = homeWorkService.findByAssess();//查询评价标签
        request.getSession().setAttribute("assess", assess);//将评价标签存到session中
        modelAndView.setViewName("./user/dianping");
        return modelAndView;
    }

    //（学生）查看学生待批改的作业
    @RequestMapping("/findNotCommentHomeworkByStudent")
    public String findNotCommentHomeworkByStudent(Model model, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Student student = (Student) request.getSession().getAttribute("student");
        System.out.println(student.getName());
        Page<Homework> homeworkList = homeWorkService.findNotCommentHomeworkByStudent(pageNum - 1, pageSize, student.getId());
        model.addAttribute("homeworks", homeworkList);
        model.addAttribute("student", student);
        return "user/student_NotComment";
    }

    //（学生）查看学生待批改的作业
    @RequestMapping("/findNotCommentHomeworkByStudentYiBu")
    public @ResponseBody
    Page<Homework> findNotCommentHomeworkByStudentYiBu(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Student student = (Student) request.getSession().getAttribute("student");
        Page<Homework> homeworkList = homeWorkService.findNotCommentHomeworkByStudent(pageNum - 1, pageSize, student.getId());
        return homeworkList;
    }

    //（学生）查看学生要修改的待批改作业
    @RequestMapping("/updateNotCommentHomeworkByStudentPre")
    public String updateNotCommentHomeworkByStudentPre(Model model, HttpServletRequest request, Long homeworkId) {
        Student student = (Student) request.getSession().getAttribute("student");
        Homework homework = homeWorkService.findById(homeworkId);
        model.addAttribute("homework", homework);
        List<Student> students = studentService.addPre(student.getId());
        model.addAttribute("students", students);
        List<Dictionary> contents = studentService.findByContent();
        List<Dictionary> tags = studentService.findByTags();
        model.addAttribute("contents", contents);
        model.addAttribute("tags", tags);
        return "user/shangchuan_update";
    }

    //（学生）学生修改待批改作业
    @RequestMapping("/updateNotCommentHomeworkByStudent")
    public String updateNotCommentHomeworkByStudent(Model model, Homework homework, Long[] studentId) {
        homeWorkService.updateNotCommentHomeworkByStudent(homework, studentId);
        return "redirect:/user/homework/findNotCommentHomeworkByStudent";
    }

    //（学生）学生删除待批改作业
    @RequestMapping("/delNotCommentHomeworkByStudent")
    public String delNotCommentHomeworkByStudent(Model model, HttpServletRequest request, Long homeworkId) {
        homeWorkService.delNotCommentHomeworkByStudent(homeworkId, (Student) request.getSession().getAttribute("student"));
        return "redirect:/user/homework/findNotCommentHomeworkByStudent";
    }

    //（学生）查看学生已批改的作业
    @RequestMapping("/findAlreadyCommentHomeworkByStudent")
    public String findAlreadyCommentHomeworkByStudent(Model model, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Student student = (Student) request.getSession().getAttribute("student");
        Page<Homework> homeworkList = homeWorkService.findAlreadyCommentHomeworkByStudent(pageNum - 1, pageSize, student.getId());
        model.addAttribute("student", student);
        model.addAttribute("homeworks", homeworkList);
        return "user/student_AlreadyComment";
    }

    //（学生）查看学生已批改的作业
    @RequestMapping("/findAlreadyCommentHomeworkByStudentYiBu")
    public @ResponseBody
    Page<Homework> findAlreadyCommentHomeworkByStudentYiBu(Model model,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Student student = (Student) request.getSession().getAttribute("student");
        Page<Homework> homeworkList = homeWorkService.findAlreadyCommentHomeworkByStudent(pageNum - 1, pageSize, student.getId());
        return homeworkList;
    }

    //老师点评作业
    @RequestMapping("/commentHomework")
    public String commentHomework(Homework homework, HttpServletRequest request,ModelMap map) {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        homeWorkService.commentHomework(homework, teacher.getId());
        Homework homework1 = homeWorkService.findByTeacherIdAndChecked(teacher.getId());
        if (homework1==null){
            return "redirect:/user/homework/findNotCommentHomeworkByTeacher";
        }else {
            return "redirect:/user/homework/findById?teacherId="+teacher.getId()+"&homeworkId="+homework1.getId();
       }

    }

    //（老师）查看老师待批改的作业
    @RequestMapping("/findNotCommentHomeworkByTeacher")
    public ModelAndView findNotCommentHomeworkByTeacher(Long classId, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        Page<Homework> homeworkList = homeWorkService.findNotCommentHomeworkByTeacher(pageNum - 1, pageSize, teacher.getId(),classId);
        Teacher teacher1 = teacherService.findById(teacher.getId());
        List<Classes> classesList = teacher1.getClassesList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.getModel().put("homeworks", homeworkList);
        modelAndView.getModel().put("teacher", teacher);
        modelAndView.getModel().put("classes",classesList);
        modelAndView.getModel().put("classId",classId);
        modelAndView.setViewName("/user/teacher_NotComment");
        return modelAndView;
    }

    //（老师）查看老师待批改的作业
    @RequestMapping("/findNotCommentHomeworkByTeacherYiBu")
    public
    @ResponseBody Page<Homework> findNotCommentHomeworkByTeacherYiBu( Long classId, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        Page<Homework> homeworks = homeWorkService.findNotCommentHomeworkByTeacher(pageNum - 1, pageSize, teacher.getId(),classId);
        return homeworks;
    }

    //（老师）查看老师已批改的作业
    @RequestMapping("/findAlreadyCommentHomeworkByTeacher")
    public String findAlreadyCommentHomeworkByTeacher(Model model, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        Page<Homework> homeworkList = homeWorkService.findAlreadyCommentHomeworkByTeacher(pageNum - 1, pageSize, teacher.getId());
        model.addAttribute("homeworks", homeworkList);
        model.addAttribute("teacher", teacher);
        return "user/teacher_AlreadyComment";
    }

    //（老师）查看老师已批改的作业
    @RequestMapping("/findAlreadyCommentHomeworkByTeacherYiBu")
    public @ResponseBody
    List<Homework> findAlreadyCommentHomeworkByTeacherYiBu(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "4") int pageSize, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        Page<Homework> homeworkList = homeWorkService.findAlreadyCommentHomeworkByTeacher(pageNum - 1, pageSize, teacher.getId());
        return homeworkList.getContent();
    }

    //进入查询作业页面
    @RequestMapping("/findAll")
    public ModelAndView findAll(HttpServletRequest request, String keyWords) {
        ModelAndView modelAndView = new ModelAndView();
        Page<Homework> all = homeWorkService.findAllHomeWork(null, null, null, null, null, null, null, 20, 1, null, null, null);//作业
        //放在session中
        List<School> schools = schoolService.findAll();//查询所有学校
        List<Dictionary> type = homeWorkService.findByType();//查询所有标签
        List<Dictionary> content = homeWorkService.findByContent();//查询所有内容
        List<Dictionary> form = homeWorkService.findByForm();//查询所有类型
        request.getSession().setAttribute("schools", schools);
        request.getSession().setAttribute("type", type);
        request.getSession().setAttribute("content", content);
        request.getSession().setAttribute("form", form);
        modelAndView.getModelMap().addAttribute("homeWork", all.getContent());
        modelAndView.getModelMap().addAttribute("keyWords", keyWords);
        modelAndView.getModelMap().addAttribute("count", all.getTotalElements());
        modelAndView.setViewName("user/zuoye");
        return modelAndView;
    }

    // 复杂异步查询作业
    @RequestMapping("/findHomework")
    public @ResponseBody
    Page<Homework> findHomework(Long xueXiao, //校区id
                                Long banji, // 班级
                                Long xuesheng, // 学生
                                String startTime, // 开始时间
                                String endTime,   // 结束时间
                                String paixu,      // 排序
                                String keyWords,//关键字
                                @RequestParam(defaultValue = "20") Integer pageSize, // 每页条数
                                @RequestParam(defaultValue = "1") Integer pageNum,   // 页数
                                @RequestParam(value = "biaoqian[]", required = false) List<String> biaoqian, // 标签
                                @RequestParam(value = "neirong[]", required = false) List<String> neirong,   // 内容
                                @RequestParam(value = "leixing[]", required = false) List<String> leixing) throws ParseException { // 类型
        Page<Homework> homeworks = homeWorkService.findAllHomeWork(xueXiao, banji, xuesheng, startTime, endTime, paixu, keyWords, pageSize, pageNum, biaoqian, neirong, leixing);//所有作业
        return homeworks;
    }

    //模糊查询作业
    @RequestMapping("/findByWorkName")
    public ModelAndView findByWorkName(String workName, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        List<Homework> homework = homeWorkService.findByWorkName(workName);
        if (homework == null) {
            modelAndView = findAll(request, null);//service有判断
            return modelAndView;
        } else {
            modelAndView.getModelMap().addAttribute("count", homework.size());
            modelAndView.getModelMap().addAttribute("homeWork", homework);
            modelAndView.setViewName("user/zuoye");
            return modelAndView;
        }
    }


}
